package com.tedu.controller;

import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.tedu.model.Category;
import com.tedu.model.Img;
import com.tedu.model.Product;
import com.tedu.service.ICategoryService;
import com.tedu.service.IImgService;
import com.tedu.service.IProductService;

@Controller
@RequestMapping("/product")
public class ProductController {
	private ICategoryService categoryService;
	private IProductService productService;
	private IImgService imgService;

	@Resource
	public void setCategoryService(ICategoryService categoryService) {
		this.categoryService = categoryService;
	}

	@Resource
	public void setProductService(IProductService productService) {
		this.productService = productService;
	}

	@Resource
	public void setImgService(IImgService imgService) {
		this.imgService = imgService;
	}

	/**
	 * 后台跳转到添加商品页面 对类别的添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		// 获取所有的类别
		List<Category> categories = categoryService.list();
		model.addAttribute("categories", categories);
		model.addAttribute(new Product());
		return "admin/product/add";
	}

	/**
	 * 后台具体的添加商品操作
	 * 
	 * 做了修改传递了状态参数
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Product product, Integer status, Integer cid, MultipartFile files[], HttpServletRequest req) {
		// 获取商品类别
		Category category = categoryService.load(cid);
		product.setCategory(category);
		// 获取商品状态
		product.setStatus(status);
		// 保存商品
		productService.add(product);
		// 获取商品图片上传的路径
		String path = req.getSession().getServletContext().getRealPath("/image");
		if (files != null) {
			for (MultipartFile file : files) {
				// 得到图片的名字
				String fileName = file.getOriginalFilename();
				File f = new File(path + "/" + fileName);
				try {
					FileUtils.copyInputStreamToFile(file.getInputStream(), f);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				/* 添加循环 狄克 */

				if (fileName != "") {
					Img img = new Img();
					img.setName(fileName);
					img.setProduct(product);
					imgService.add(img);
				}
			}
		}
		return "redirect:/product/products";
	}

	/**
	 * 前台查询商品详细信息
	 */
	@RequestMapping(value = "/{id}/item", method = RequestMethod.GET)
	public String productItem(@PathVariable int id, Model model) {
		Product product = productService.productItem(id);
		model.addAttribute(product);
		return "client/product_item";
	}

	/**
	 * 后台查询所有商品
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/products", method = RequestMethod.GET)
	public String list(Model model, HttpServletRequest request) throws UnsupportedEncodingException {
		// ----------------------------------------狄克
		List<Product> products = productService.list();
		model.addAttribute("products", products);
		return "admin/product/list";
	}

	@RequestMapping(value = "/{id}/delete", method = RequestMethod.DELETE)
	public String delete(@PathVariable int id) {
		// 先删除所有含有product_id的图片，才不会冲突--狄克
		imgService.alldelete(id);
		productService.delete(id);
		return "redirect:/product/products";
	}

	/**
	 * 跳转修改页面 狄克
	 */
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String update(@PathVariable int id, Model model) {
		// 获取所有的类别
		List<Category> categories = categoryService.list();
		model.addAttribute("categories", categories);
		// 显示类别名称
		int cid = productService.load(id).getCategory().getId();
		model.addAttribute("categoryname", categoryService.load(cid).getName());
		model.addAttribute("product", productService.load(id));
		return "admin/product/update";
	}

	/**
	 * 修改商品属性 狄克
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public String update(@PathVariable int id, Product product, Integer status, Integer cid) {
		// 获取商品类别
		Category category = categoryService.load(cid);
		product.setCategory(category);
		// 获取商品状态
		product.setStatus(status);
		// 保存商品
		productService.update(product);
		return "redirect:/product/products";
	}

	/**
	 * 跳转图片页面 狄克
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String picture(@PathVariable int id, Model model) {
		List<Img> imgs = imgService.list(id);
		model.addAttribute("imgs", imgs);
		model.addAttribute("product", productService.load(id));
		return "admin/product/imgs";
	}

	/**
	 * 添加图片 狄克
	 */
	@RequestMapping(value = "/{id}/addimg", method = RequestMethod.POST)
	public String addpicture(@PathVariable int id, MultipartFile files[], HttpServletRequest req) {

		Product product = productService.load(id);
		// 获取商品图片上传的路径
		String path = req.getSession().getServletContext().getRealPath("/image");
		if (files != null) {
			for (MultipartFile file : files) {
				// 得到图片的名字
				String fileName = file.getOriginalFilename();
				File f = new File(path + "/" + fileName);
				try {
					FileUtils.copyInputStreamToFile(file.getInputStream(), f);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				/* 添加判断不为空 狄克 */

				if (fileName != "") {
					List<Img> imgs = imgService.list(id);
					// 判断同名不能添加
					int i;
					for (i = 0; i < imgs.size(); i++) {
						if (imgs.get(i).getName().equals(fileName)) {
							break;
						}
					}
					if (i == imgs.size()) {
						Img img = new Img();
						img.setName(fileName);
						img.setProduct(product);
						imgService.add(img);
					}
				}
			}
		}
		return "redirect:/product/" + product.getId();
	}

	/**
	 * 删除图片 狄克
	 */
	@RequestMapping(value = "/{id}/deleteimg", method = RequestMethod.DELETE)
	public String deleteimg(@PathVariable int id) {
		Product product = productService.load(imgService.load(id).getProduct().getId());
		imgService.delete(id);
		return "redirect:/product/" + product.getId();
	}

	/**
	 * 模糊搜索商品 狄克
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/selectproduct", method = RequestMethod.GET)
	public String selectproduct(HttpServletRequest request, Model model) throws UnsupportedEncodingException {

		String str = request.getParameter("str");
		String style = request.getParameter("style");
		List<Product> products = productService.list();

		if (style.equals("0")) {
			products = productService.selectProductsName(str);
		} else if (style.equals("1")) {
			int str1 = 4;
			if (str.equals("下架")) {
				str1 = 0;
			} else if (str.equals("普通")) {
				str1 = 1;
			} else if (str.equals("热销")) {
				str1 = 2;
			} else if (str.equals("特色")) {
				str1 = 3;
			}
			products = productService.selectProductsStatus(str1);
		} else if (style.equals("2")) {
			products = productService.selectProductsCategory(str);
		} else if (style.equals("3")) {
			double str1 = Double.parseDouble(str);
			DecimalFormat df = new DecimalFormat("#.00");
			System.out.println(df.format(str1));

			products = productService.selectProductsDiscount(str1);
		}
		model.addAttribute("products", products);
		model.addAttribute("name", str);
		model.addAttribute("style", style);
		return "admin/product/list";
	}

	/////////////////////////////
	// 新项目
	@RequestMapping(value = "/{target}/more", method = RequestMethod.GET)
	public String moreProducts(@PathVariable String target, Model model) {
		List<Product> products = null;
		String reqSource = null;
		if ("discountProducts".equals(target)) {
			products = productService.listAllProductOfDiscount();
			reqSource = "discountProducts";
		}
		if ("featuredProducts".equals(target)) {
			products = productService.listAllProductByFeature(3);
			reqSource = "featuredProducts";
		}
		if ("hotSaleProducts".equals(target)) {
			products = productService.listAllProductByFeature(2);
			reqSource = "hotSaleProducts";
		}
		model.addAttribute("products", products);
		model.addAttribute("reqSource", reqSource);
		return "client/product_more";
	}

	@RequestMapping(value = "/fuzzy", method = RequestMethod.POST)
	public String fuzzyQuery(String reqSource, String name, Model model) {
		List<Product> products = null;
		String newReqSource = null;
		if ("index".equals(reqSource)) {
			products = productService.fuzzyQueryAll(name);
			newReqSource = "index";
		}
		if ("discountProducts".equals(reqSource)) {
			System.out.println("文本框：" + name);
			products = productService.fuzzyQueryDiscountProducts(name);
			newReqSource = "discountProducts";
		}
		if ("featuredProducts".equals(reqSource)) {
			System.out.println("文本框：" + name);
			products = productService.fuzzyQueryByFeature(name, 3);
			newReqSource = "featuredProducts";
		}
		if ("hotSaleProducts".equals(reqSource)) {
			System.out.println("文本框：" + name);
			products = productService.fuzzyQueryByFeature(name, 2);
			newReqSource = "hotSaleProducts";
		}
		model.addAttribute("products", products);
		model.addAttribute("reqSource", newReqSource);
		return "client/product_more";

	}

	@RequestMapping(value = "/{cid}/category", method = RequestMethod.GET)
	public String queryByCategory(@PathVariable int cid, Model model) {
		List<Product> products = productService.queryByCategory(cid);
		System.out.println("分类显示");
		model.addAttribute("products", products);
		model.addAttribute("cid", cid);
		return "client/category";
	}

	@RequestMapping(value = "/fuzzyQueryByCategory", method = RequestMethod.POST)
	public String fuzzyQueryByCategory(int cid, String name, Model model) {
		List<Product> products = productService.fuzzyQueryByCategory(cid, name);
		System.out.println("分类产品模糊查询");
		model.addAttribute("products", products);
		model.addAttribute("cid", cid);
		return "client/category";
	}

}
